package api

import (
	"bbs-go/internal/pkg/common"
	"bbs-go/internal/services"
	"bbs-go/internal/services/cache"
	"time"

	"github.com/kataras/iris/v12"
)

type StatsController struct {
	Ctx iris.Context
}

// 获取统计数据
func (c *StatsController) GetStats() *common.JsonResult {
	// 用户活跃度统计
	userStats := map[string]interface{}{
		"todayNewUsers": services.UserService.GetTodayNewUserCount(),
		"activeUsers":   services.UserService.GetActiveUserCount(),
		"todayPosts":    services.TopicService.GetTodayPostCount(),
	}

	// 内容运营统计
	contentStats := map[string]interface{}{
		"todayPosts":    services.TopicService.GetTodayPostCount(),
		"todayComments": services.CommentService.GetTodayCommentCount(),
		"todayLikes":    services.UserLikeService.GetTodayLikeCount(),
		"totalPosts":    services.TopicService.GetTotalPostCount(),
		"totalComments": services.CommentService.GetTotalCommentCount(),
		"totalLikes":    services.UserLikeService.GetTotalLikeCount(),
	}

	// 系统运营统计
	systemStats := map[string]interface{}{
		"visits":          cache.VisitCache.GetVisitCount(),
		"avgResponseTime": cache.SystemCache.GetAvgResponseTime(),
		"onlineUsers":     cache.UserCache.GetOnlineUserCount(),
	}

	return common.JsonData(map[string]interface{}{
		"userStats":    userStats,
		"contentStats": contentStats,
		"systemStats":  systemStats,
	})
}

// 获取用户活跃度趋势
func (c *StatsController) GetUserActivityTrend() *common.JsonResult {
	days := 7
	dates := make([]string, days)
	counts := make([]int64, days)

	now := time.Now()
	for i := 0; i < days; i++ {
		date := now.AddDate(0, 0, -i)
		dates[days-1-i] = date.Format("01-02")
		counts[days-1-i] = services.UserService.GetActiveUserCountByDate(date)
	}

	return common.JsonData(map[string]interface{}{
		"dates":  dates,
		"counts": counts,
	})
}

// 获取内容发布趋势
func (c *StatsController) GetContentTrend() *common.JsonResult {
	days := 7
	dates := make([]string, days)
	postCounts := make([]int64, days)
	commentCounts := make([]int64, days)

	now := time.Now()
	for i := 0; i < days; i++ {
		date := now.AddDate(0, 0, -i)
		dates[days-1-i] = date.Format("01-02")
		postCounts[days-1-i] = services.TopicService.GetPostCountByDate(date)
		commentCounts[days-1-i] = services.CommentService.GetCommentCountByDate(date)
	}

	return common.JsonData(map[string]interface{}{
		"dates":         dates,
		"postCounts":    postCounts,
		"commentCounts": commentCounts,
	})
}

// 获取系统性能数据
func (c *StatsController) GetSystemPerformance() *common.JsonResult {
	hours := 24
	times := make([]string, hours)
	responseTimes := make([]int64, hours)

	now := time.Now()
	for i := 0; i < hours; i++ {
		hour := now.Add(-time.Duration(i) * time.Hour)
		times[hours-1-i] = hour.Format("15:04")
		responseTimes[hours-1-i] = cache.SystemCache.GetResponseTimeByHour(hour)
	}

	return common.JsonData(map[string]interface{}{
		"times":         times,
		"responseTimes": responseTimes,
	})
}
